# coding: utf-8

from leancloud import Object
from leancloud import File
from leancloud import Query
from leancloud import LeanCloudError
from leancloud import User
from flask import request
from datetime import datetime
import time
import os
from werkzeug.utils import secure_filename
import json

class FarmerSayItem(Object):
    pass


class MFollowee(Object):
    pass


class MFollower(Object):
    pass


class SubSay():

    # 获取最新的说说
    def getSubNewSay(self):
        user = request.json['user']
        pubTime = request.json['time']
        req_count = request.json['count']
        if (req_count < 10):
            req_count = 10
        if (req_count > 40):
            req_count = 40
        print pubTime
        try:
            mFollowees = Query(MFollowee).equal_to("user", user).descending('createdAt').find()
            values = []
            for mFollowee in mFollowees:
                values.append(mFollowee.get('followee'))
            print values
            farmerSayItems = Query(FarmerSayItem).contained_in("name", values).descending('createdAt').find()
        except LeanCloudError, e:
            if e.code == 101:  # 服务端对应的 Class 还没创建
                farmerSayItems = []
            else:
                raise e
        resultItems = []
        item_count = 0;
        for farmerSayItem in farmerSayItems:
            item_count = item_count + 1
            if (item_count >= req_count):
                break
            imgurls = []
            resultItem = {}
            followee = farmerSayItem.get('name')
            try:
                mFollowees = Query(MFollowee).equal_to("user", user).equal_to("followee", followee).descending(
                        'createdAt').find()
                count = len(mFollowees)
                if (count > 0):
                    resultItem["followed"] = 1
                else:
                    resultItem["followed"] = 0
            except LeanCloudError, e:
                if e.code == 101:  # 服务端对应的 Class 还没创建
                    mFollowees = []
                else:
                    raise e
            resultItem['time'] = farmerSayItem.get("time")
            resultItem['name'] = followee
            resultItem['objectId'] = farmerSayItem.id

            commentStr = str(farmerSayItem.get('comments'))
            if commentStr.strip() == '':
                comments = []
            else:
                comments = eval(commentStr)

            favorterStr = farmerSayItem.get('favorters')
            if favorterStr == None:
                favorters = []
            else:
                favorters = eval(favorterStr)

            resultItem['comments'] = comments
            resultItem['favorters'] = favorters
            try:
                mUsers = Query(User).equal_to("username", followee).descending(
                        'createdAt').find()
                count = len(mUsers)
                if (count > 0):
                    fil = mUsers[0].get('avatar')
                    if (fil != None):
                        url = fil.url
                    else:
                        url = None
            except LeanCloudError, e:
                url = None
                if e.code == 101:  # 服务端对应的 Class 还没创建
                    mUsers = []
                else:
                    raise e

            resultItem['avatar'] = url
            count = farmerSayItem.get('count')
            resultItem['imgCount'] = count
            resultItem['content'] = farmerSayItem.get('content')

            for i in range(1, count + 1):
                img = farmerSayItem.get('img' + str(i))
                imgurls.append(img.url)
            resultItem['imgUrls'] = imgurls
            resultItems.append(resultItem)
            pass
        data = {'code': 200, 'farmersayItems': resultItems, "time_now": long(time.time() * 1000)}
        print "new: " + str(req_count)
        return json.dumps(data, indent=1)
        pass



       # 获取最新的说说
    def getSubOldSay(self):
        user = request.json['user']
        pubTime = request.json['time']
        print pubTime
        try:
            mFollowees = Query(MFollowee).equal_to("user", user).descending('createdAt').find()
            values = []
            for mFollowee in mFollowees:
                values.append(mFollowee.get('followee'))
            print values
            farmerSayItems = Query(FarmerSayItem).contained_in("name", values).less_than("time",pubTime).descending('createdAt').find()
        except LeanCloudError, e:
            if e.code == 101:  # 服务端对应的 Class 还没创建
                farmerSayItems = []
            else:
                raise e
        resultItems = []
        item_count = 0
        for farmerSayItem in farmerSayItems:
            item_count = item_count + 1
            if(item_count >= 10):
                break
            imgurls = []
            resultItem = {}
            followee = farmerSayItem.get('name')
            try:
                mFollowees = Query(MFollowee).equal_to("user", user).equal_to("followee", followee).descending(
                        'createdAt').find()
                count = len(mFollowees)
                if (count > 0):
                    resultItem["followed"] = 1
                else:
                    resultItem["followed"] = 0
            except LeanCloudError, e:
                if e.code == 101:  # 服务端对应的 Class 还没创建
                    mFollowees = []
                else:
                    raise e
            resultItem['time'] = farmerSayItem.get("time")
            resultItem['name'] = followee
            resultItem['objectId'] = farmerSayItem.id

            commentStr = str(farmerSayItem.get('comments'))
            if commentStr.strip() == '':
                comments = []
            else:
                comments = eval(commentStr)

            favorterStr = farmerSayItem.get('favorters')
            if favorterStr == None:
                favorters = []
            else:
                favorters = eval(favorterStr)

            resultItem['comments'] = comments
            resultItem['favorters'] = favorters
            try:
                mUsers = Query(User).equal_to("username", followee).descending(
                        'createdAt').find()
                count = len(mUsers)
                if (count > 0):
                    fil = mUsers[0].get('avatar')
                    if (fil != None):
                        url = fil.url
                    else:
                        url = None
            except LeanCloudError, e:
                url = None
                if e.code == 101:  # 服务端对应的 Class 还没创建
                    mUsers = []
                else:
                    raise e

            resultItem['avatar'] = url
            count = farmerSayItem.get('count')
            resultItem['imgCount'] = count
            resultItem['content'] = farmerSayItem.get('content')

            for i in range(1, count + 1):
                img = farmerSayItem.get('img' + str(i))
                imgurls.append(img.url)
            resultItem['imgUrls'] = imgurls
            resultItems.append(resultItem)
            pass
        data = {'code': 200, 'farmersayItems': resultItems, "time_now": long(time.time() * 1000)}
        print 'old sub say'
        return json.dumps(data, indent=1)
        pass

      # 获取最新的说说
    def getToSub(self):
        user = request.json['user']
        pubTime = request.json['time']
        print pubTime
        try:
            farmerSayItems = Query(FarmerSayItem).descending('createdAt').find()
        except LeanCloudError, e:
            if e.code == 101:  # 服务端对应的 Class 还没创建
                farmerSayItems = []
            else:
                raise e
        resultItems = []
        for farmerSayItem in farmerSayItems:
            imgurls = []
            resultItem = {}
            followee = farmerSayItem.get('name')

            if(self.contains(resultItems,followee)):
                continue
            try:
                mFollowees = Query(MFollowee).equal_to("user", user).equal_to("followee", followee).descending(
                        'createdAt').find()
                count = len(mFollowees)
                if (count > 0):
                    resultItem["followed"] = 1
                else:
                    resultItem["followed"] = 0
            except LeanCloudError, e:
                if e.code == 101:  # 服务端对应的 Class 还没创建
                    mFollowees = []
                else:
                    raise e
            resultItem['time'] = farmerSayItem.get("time")
            resultItem['name'] = followee
            resultItem['objectId'] = farmerSayItem.id

            commentStr = str(farmerSayItem.get('comments'))
            if commentStr.strip() == '':
                comments = []
            else:
                comments = eval(commentStr)

            favorterStr = farmerSayItem.get('favorters')
            if favorterStr == None:
                favorters = []
            else:
                favorters = eval(favorterStr)

            resultItem['comments'] = comments
            resultItem['favorters'] = favorters
            try:
                mUsers = Query(User).equal_to("username", followee).descending(
                        'createdAt').find()
                count = len(mUsers)
                if (count > 0):
                    fil = mUsers[0].get('avatar')
                    if (fil != None):
                        url = fil.url
                    else:
                        url = None
            except LeanCloudError, e:
                url = None
                if e.code == 101:  # 服务端对应的 Class 还没创建
                    mUsers = []
                else:
                    raise e

            resultItem['avatar'] = url
            count = farmerSayItem.get('count')
            resultItem['imgCount'] = count
            resultItem['content'] = farmerSayItem.get('content')

            for i in range(1, count + 1):
                img = farmerSayItem.get('img' + str(i))
                imgurls.append(img.url)
            resultItem['imgUrls'] = imgurls
            resultItems.append(resultItem)
            pass
        data = {'code': 200, 'farmersayItems': resultItems, "time_now": long(time.time() * 1000)}
        print "to sub say: "
        return json.dumps(data, indent=1)
        pass

    def contains(self,items,followee):
        for item in items:
            if(followee ==  item.get('name')):
                return True
        return False
